<template>
  <div>
    数组分组
  </div>
</template>
 
<script setup lang='ts'>
import { people } from '../mock/data';
import type { peopleI } from '../mock/data'

// 按照年龄分组
function groupBy(arr: Array<any>, generateKey: Function | string) {
  if (typeof generateKey === 'string') {
    const propName = generateKey;
    generateKey = (item: any) => item[propName]
  }

  const res: Array<any> = []
  for (const item of arr) {
    const key = generateKey(item)
    if (!res[key]) {
      res[key] = []
    }
    res[key].push(item)
  }

  return res
}


const res: Array<peopleI> = groupBy(people, ((item: peopleI) => item.age))
const res1: Array<peopleI> = groupBy(people, 'age')
console.log(res, res1)


</script>
 
<style lang='scss' scoped>

</style>